<template>
  <div class="profile-container">
    <!-- 用户信息卡片 -->
    <el-card class="user-profile">
      <div class="profile-header">
        <el-avatar :size="80" :src="userInfo.avatar" />
        <div class="profile-meta">
          <h1 class="username">{{ userInfo.nickName }}</h1>
          <div class="stats">
            <el-tag type="info">
              <el-icon><User /></el-icon>
              注册时间：{{ formatDate(userInfo.createTime) }}
            </el-tag>
            <el-tag type="success">
              <el-icon><Collection /></el-icon>
              知识库：{{ userInfo.libraryCount || 0 }}
            </el-tag>
            <el-tag type="warning">
              <el-icon><Document /></el-icon>
              文章：{{ userInfo.articleCount || 0 }}
            </el-tag>
          </div>
          <!-- 新增关注按钮 -->
          <el-button 
            class="follow-btn"
            :type="isFollowing ? 'info' : 'primary'" 
            @click="handleFollow"
          >
            {{ isFollowing ? '已关注' : '关注' }}
          </el-button>
          <p class="bio" v-if="userInfo.bio">{{ userInfo.bio }}</p>
        </div>
      </div>
    </el-card>

    <!-- 知识库列表 -->
    <div class="library-section">
      <h2 class="section-title">创建的知识库（{{ libraries.length }}）</h2>
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      <template v-else>
        <div v-if="libraries.length > 0" class="library-grid">
          <library-card
            v-for="lib in libraries"
            :key="lib.libraryId"
            :library="lib"
             @click="handleCardClick(lib)"
            class="library-item"
          />
        </div>
        <el-empty v-else description="该用户暂未创建知识库" />
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { User, Collection, Document } from '@element-plus/icons-vue'
import require from '../require'
import LibraryCard from './LibraryCard.vue'
import { useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute()
const userId = ref(route.query.userId)

// 用户信息
const userInfo = ref({
  nickName: '',
  avatar: '',
  bio: '',
  createTime: '',
  libraryCount: 0,
    articleCount: 0,
    isFollow: false,
})

// 知识库列表
const libraries = ref([])
const loading = ref(true)
// 新增响应式状态
const isFollowing = ref(false)

// 获取用户信息
const fetchUserInfo = async () => {
    try {
    const e = userId.value
      const res = await require.post('user/getUserInfo', { userId: e })
    userInfo.value = {
        nickName: res.user.nickName,
        avatar: res.user.avatarUrl,
        createTime: new Date(res.user.createTime).toLocaleDateString(),
        libraryCount: res.user.libraryAmount,
        articleCount: res.user.articleAmount,
        isFollowing: res.user.isFollowed,
    }
    // 新增关注状态获取
    isFollowing.value = res.user.isFollowed || false
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取知识库列表
const fetchLibraries = async () => {
  try {
    loading.value = true
      const res = await require.post('user/getUserLibraryList', {
      userId: userId.value,
      })
      const alist = [];
      for (let i = 0; i < res.libraryAmount; i++) {
          const e = res.libraryList[i];
          alist.push({
              libraryId: e.libraryId,
              name: e.libraryName,
              description: e.description,
              articleCount: e.articleAmounts,
              createTime: e.createTime,
              updateTime: e.updateTime,
              creatorId: e.creatorUser.userId,
              isPublic: e.isPublic,
              likedAmounts: e.likedAmounts, // 确保有这些属性
              collectedAmounts: e.collectedAmounts,
              commentedAmounts: e.commentedAmounts,
              currentUserCollect: e.currentUserCollect,
              currentUserLike: e.currentUserLike,
          });
      }
    libraries.value = alist
  } catch (error) {
    console.error('获取知识库失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理行点击事件
const handleCardClick = (row) => {
    // 生成包含 query 参数的路由对象
    const r = router.resolve({
        name: 'HisLibrary', // 文章详情页路由名
        query: { id: row.libraryId }
    });
    // 在新标签页打开路由链接
    window.open(r.href, '_blank');
};

// 监听路由参数变化
watch(() => route.query.userId, (newVal) => {
  userId.value = newVal
  fetchUserInfo()
  fetchLibraries()
})

onMounted(async () => {
  await fetchUserInfo()
  await fetchLibraries()
})

// 格式化日期
const formatDate = (dateStr) => {
  return dateStr || '未知时间'
}

import { UserStore } from '../store/user'

// 新增关注操作方法
const handleFollow = async () => {
    try {
        const userStore = UserStore()
        if (userId.value === userStore.userInfo.userId) {
            ElMessage.warning('不能关注自己')
            return
        }
      const res = await require.post('user/followUser', { 
          userId: userId.value 
    })
    isFollowing.value = res.followed
    ElMessage.success(isFollowing.value ? '关注成功' : '已取消关注')
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.user-profile {
  margin-bottom: 30px;
  border-radius: 12px;
}

.profile-header {
  display: flex;
  gap: 30px;
  align-items: center;
  padding: 20px;
}

.profile-meta {
  flex: 1;
}

.username {
  margin: 0 0 15px 0;
  font-size: 2em;
  color: #303133;
}

.stats {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.bio {
  color: #606266;
  line-height: 1.6;
  margin: 15px 0 0;
}

.library-section {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.section-title {
  color: #303133;
  margin-bottom: 25px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e4e7ed;
}

.library-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.loading-container {
  padding: 30px 0;
}

.follow-btn {
  margin-top: 15px;
  width: 120px;
  font-weight: 500;
  letter-spacing: 1px;
}
</style>
